import prisma from '../prisma/index.js'

export const getPostsService = async (title, skip, pagesize) => {
  try {
    return await prisma.post.findMany({
      where: {
        title: {
          contains: title,
        },
      },
      include: {
        topic: {
          select: {
            name: true
          }
        },
        _count: {
          select: {
            comments: true
          }
        }
      },
      skip,
      take: pagesize,
    });
  } catch (err) {
    throw err;
  }
}

export const getPostService = async (id) => {
  try {
    return await prisma.post.findUnique({
      where: { id },
      include: {
        topic: {
          select: {
            name: true
          }
        },
        comments: true,
        _count: {
          select: {
            comments: true
          }
        }
      },
    });
  } catch (err) {
    throw err;
  }
}

export const postPostService = async (data) => {
  try {
    return await prisma.post.create({
      data,
    });
  } catch (err) {
    throw err;
  }
}

export const patchPostService = async (id, data) => {
  try {
    return await prisma.post.update({
      where: { id },
      data,
    });
  } catch (err) {
    throw err;
  }
}

export const deletePostService = async (id) => {
  try {
    return await prisma.post.deleteMany({
      where: { id },
    });
  } catch (err) {
    throw err;
  }
}
